const express = require('express')
const router = express.Router()

const Comment = require('../../models/Comment')
const Article = require('../../models/Article')
const lodash = require('lodash')
const cloneDeep = lodash.cloneDeep

// 统一返回格式
let responseData 

// 获取所有评论
router.get('/', function(req, res) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	Comment.find().then((commentList) => {

		let result = []
		let temp = {}
		Article.find().then(function(articleList) {
			function getResult(tree, parentId, articleId) {
				tree.forEach((item, index) => {
					result.push({
						_id: item._id,
				        articleId: item.articleId || articleId,
				        articleTitle: temp[item.articleId || articleId],
				        nickName: item.nickName,
				        email: item.email,
				        content: item.content,
				        time: item.time,
				        parentId: parentId
					})
					if(item.children) {
						getResult(item.children, item._id, item.articleId)
					}
				})
			}
			articleList.forEach((item) => {
				console.log(item._id)
				temp[item._id] = item.articleTitle
			})
			console.log(temp)

			getResult(commentList, null)

			responseData.data.commentList = result
			res.json(responseData)
		})


	})
})

// 删除某一条评论
// 参数：父级ID: _id    发表时间： time
router.get('/delete', function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	const _id = req.query._id
	const time = req.query.time
	const isSon = req.query.isSon
	console.log(_id, time, isSon)
	Comment.findOne({
		_id
	}).then(function(commentInfo) {
		console.log(commentInfo)
		if(isSon == 'true') {
			let children = commentInfo.children
			let temp = cloneDeep(children)
			temp.forEach((item, index) => {
				item.time == time && children.splice(index, 1)
			})
			Comment.update({
				_id
			}, {
				children: children
			}).then(function(err) {
				console.log(err)
				res.json(responseData)
			})
		}else {
			console.log(2)
			Comment.deleteOne({
				_id
			}).then(function(err) {
				res.json(responseData)
			})
		}

	})
})


module.exports = router